package plot;
use base qw(Exporter);
use File::Basename;
use lib dirname($0) =~ /(.*)/;
use lib "/data/share/code/trunk/perl/stock/USA/analyse/lib/ChartDirector/lib/";
use perlchartdir;
use Encode 'from_to';
our @EXPORT = qw/plot/;

sub plot {
	my ($data, $x_name, $title, $png_file, $label_cnt, $op_hash) = @_;
	my @label_x = ();
	my @label_y = ();
	my @label_t = ();
	my $data_len = scalar(@$data);

	if ($label_cnt > 0) {
		foreach my $idx (0 .. $label_cnt) {
			push @label_x, int($idx * (($data_len-1) / $label_cnt));
			push @label_y, $data->[$label_x[$idx]]; 
			push @label_t, $x_name->[$label_x[$idx]]; 
		}
	}
	if (defined($op_hash)) {
		my %op_hash = %{$op_hash};
		foreach my $key (sort {$a<=>$b} keys %op_hash) {
			push @label_x, $op_hash{$key}{'x'};
			push @label_y, $op_hash{$key}{'y'};
			push @label_t, $op_hash{$key}{'value'};
		}
	}
	my $dataX = \@label_x;
	my $dataY = \@label_y;
	my $labels = \@label_t;

	my $c = new XYChart(800, 400);
	$c->setPlotArea(50, 35, 700, 330)->setGridColor(0xc0c0c0, 0xc0c0c0);
	$c->addTitle($title, "/data/share/code/trunk/perl/stock/USA/analyse/lib/ChartDirector/lib/fonts/simsun.ttc", 12);
	$c->yAxis()->setWidth(3);
	$c->xAxis()->setWidth(3);

	my $x_len = int(scalar(@$data)*1.05);
	my $x_grid = 5;
	if ($x_len <= 50)
	{$x_grid=5;} elsif ($x_len <= 100)
	{$x_grid=10;} elsif ($x_len <= 250)
	{$x_grid=25;} else {$x_grid = int($x_len / 20);}
	$c->xAxis()->setLinearScale(0, int(scalar(@$data)*1.05), $x_grid, $x_grid);

	my $layer = $c->addLineLayer2();
	$layer->addDataSet($data, 0x0000ff)->setDataSymbol($perlchartdir::SquareSymbol);
	$layer->setLineWidth(1);
	$c->yAxis()->setAutoScale(0, 0, 0);

	my $layer = $c->addScatterLayer($dataX, $dataY, "", $perlchartdir::GlassSphereShape,
			12, 0xff3333, 0xff3333);
	$layer->addExtraField($labels);
	$layer->setDataLabelFormat("{field0}");
	my $textbox = $layer->setDataLabelStyle("arialbd.ttf", 8);
	$textbox->setBackground(0xffffff, $perlchartdir::Transparent, 1);
	$textbox->setAlignment($perlchartdir::Left);
	$textbox->setPos(4, 0);

	open FV,">$png_file";
	binmode(FV);
	print FV $c->makeChart2($perlchartdir::PNG);
	close FV;
}

1;
